-----------------------------------------------------------------------------
-- 登录界面
--
---------------
-- Author: 筱迪
-- Date: 2020.12.16
-----------------------------------------------------------------------------
require "Common/define"
require "Logic/Config"
require "proto/login/message/ReqCreatePlayerMessage"
require ("View/"..PanelNames.UISysTips)
local json = require "cjson"
require "Logic/NoticeManager"

UILogin = UIBase.New(PanelResNames.UILogin)
local this = UILogin
local jsonStr;
local oldServerId;
local isInit = false;
local isClick = false;
local serverOpenTime = nil;
local serverState = nil;
local forceUpdateUrl = nil;
local isOpenTipsPanel = true;
local loginServerCount = 5;
local m_click_timer = nil

function UILogin.Init()
    UIBase.Init(this)

    showUI(PanelNames.UIScreenEffect);
    local HWR = Screen.height / Screen.width;
    print("HWR==="..HWR)
    if AppConst.UseBlackCover then
        showUI(PanelNames.UICover);

        local width = Screen.width;
        local height = Screen.height;
        width = math.ceil(width / FairyGUI.UIContentScaler.scaleFactor);
        height = math.ceil(height / FairyGUI.UIContentScaler.scaleFactor);

        Config.uiXOffset =  (width - AppConst.DesignResolutionX) / 2;

    end

    Config.SendLoginTime = 0
end

function UILogin:RefreshClickState(b)
    if isClick ~= b then
        isClick = b

        if m_click_timer then
            utimer.remove(m_click_timer)
        end

        if b then
            m_click_timer = utimer.timeCall(function()
                isClick = false
            end, 1000)
        end
    end
end

function UILogin:OnDestroy()
    if not HelperFunc.IsNull(self.par) then
        destroyImmediate(self.par)
        self.par = nil;
    end
    self:DestoryTimer()
    self:DestoryLoginTimer()
    self:DestoryHttpLoginTimer();
    isInit = false;
    jsonStr = nil;
    oldServerId = nil;
    isClick = false;
    serverOpenTime = nil;
    serverState = nil;
    forceUpdateUrl = nil;
    isOpenTipsPanel = true;
    self.isDestroy = true

    AudioManager.PlayBGMOnCloseUI("UILogin")
end

function UILogin:OnCreate()
    TAManager.TrackByDictionary("show_ui_login_panel")
    AudioManager.WwiseInit()
    Config.isU8sdkLoginOut = true

    --这里还没有登录服务器，使用的是本地时间，不精确没有大问题
    local _time = formatUnixTime2Date(os.time())
	local _timeStr = _time.year.."-".._time.month.."-".._time.day
    local _loginTime = Util.GetPlayerPrefs("loginTime")
    local _soundId = 0
    if _loginTime and _loginTime == _timeStr then
        _soundId = 5000002
    else
        _soundId = 5000001
    end
    self.isDestroy = false
    Util.SetPlayerPrefs("loginTime",_timeStr)
    AudioManager.Play(_soundId)

    self.btNotice = self:GetChild("NoticeBtn")
    self.inputAccount = self:GetChild("AccInput")
    self.pwd_input = self:GetChild("PwdInput")
    self.bt_register = self:GetChild("RegisterBtn");
    self.bt_login = self:GetChild("EnterBtn");
    self.version = self:GetChild("version");
    self.eff_login_01 = self:GetChild("eff_login_01");
    self.sdk_controller = self:GetController("sdk");
    self.sdk_controller.selectedIndex = 0
    self.Btn_SDK = self:GetChild("Btn_SDK")
    self.Btn_Repair = self:GetChild("Btn_Repair")

    local m_account_support = LoginSDK.GetInstance():GetSupportAccountCenter()
    if Application.platform == RuntimePlatform.IPhonePlayer then
        m_account_support = true;
    end
    
    if self.Btn_SDK  then
        self.Btn_SDK.visible = m_account_support
        if m_account_support then
            self.Btn_SDK:GetChild("UIRedDots"):GetController("c1").selectedIndex = logicMgr.SDKManager.GetAccountCenterCount() > 0 and 2 or 0
        end
        
    end
    self.Btn_Repair.visible = true;
    
    self.status_controllder = self:GetChild("Btn_SelectServer"):GetController("type");

    self:GetChild("Btn_SelectServer").visible = false

    self.server_name = self:GetChild("Btn_SelectServer"):GetChild("Text_ServerName");

    self:GetChild("Btn_SelectServer"):GetChild("Text_ServerName").text = ""
    local ctrlPA = self:GetController("PA")
    if ctrlPA then
        if AppConst.drawingState == 0 then
            ctrlPA.selectedIndex = 0
        else
            ctrlPA.selectedIndex = 1
        end
    end
    self:InitView()
    self:BindEvent()
    resMgr:LoadModelPrefab("UIEff/UI_Login_01", function(go)
        if self.parDraw == nil then
            self.parDraw = GoWrapper.New()
        end
        if not HelperFunc.IsNull(self.par) then
            destroyImmediate(self.par)
        end
        self.par = newObject(go);
        self.par:SetActive(true);
        self.par:AddComponent(TCanvas);
        self.par:AddComponent(TChangeSortingOrder);
        self.parDraw:SetWrapTarget(self.par,false)
        self.eff_login_01:SetNativeObject(self.parDraw)
    end)
    Time.timeScale = 1
end

function UILogin:InitView()
    --local wifi = Util.IsWifi;
    --local net = Util.NetAvailable;

    LoginSDK.GetInstance():SetiOSAppIconBadgeNumber(0);
    self.version.text = "V"..AppConst.appVersion
    local _isShowAccountText = true
    if (Application.platform == RuntimePlatform.Android or Application.platform == RuntimePlatform.IPhonePlayer) and Config.isOpenSDK then
        self.sdk_controller.selectedIndex = 1
        if Application.platform == RuntimePlatform.IPhonePlayer then
            print("登录清除==========iOS推送标记")
            JPush.JPushBinding.SetBadge(0);
        end
        _isShowAccountText = false
        self:DestoryTimer()
        self.mTimer = utimer.delayCall(function()
            if Application.platform == RuntimePlatform.IPhonePlayer then
                if LoginSDK.GetInstance():IsU8Init() and not isInit then
                    isInit = true
                    utimer.delayCall(function()
                        SDKManager.Login()
                    end, 1300)
                end
            else
                if true --[[LoginSDK.GetInstance():IsU8Init()]] then
                    utimer.delayCall(function()
                        SDKManager.Login()
                    end, 1300)
                end
            end
        end,500)
        return
    end
    self.inputAccount.visible = _isShowAccountText
    self:InitAccount()
    Config.ReplaceTestingEnvironmentUrl();
    if (Application.platform == RuntimePlatform.Android or Application.platform == RuntimePlatform.IPhonePlayer) and Config.isOpenSDK then

    else
        --self.sdk_controller.selectedIndex = 1
        logicMgr.LoginManager.HttpToServerInfo(function()

        end, EnumConst.LoginPlatform.PC);
    end
end

function UILogin:Refresh()
    --local default = logicMgr.LoginManager.GetDefaultServerInfo()
    --
    --if default then
    --    if default.state == Server_ENU_State.Repair then
    --        self.status_controllder.selectedIndex = 3
    --    elseif default.state == Server_ENU_State.Full then
    --        self.status_controllder.selectedIndex = 1
    --    elseif default.state == Server_ENU_State.Fluent then
    --        self.status_controllder.selectedIndex = 0
    --    end
    --    self:GetChild("Btn_SelectServer"):GetChild("Text_ServerName").text = default.name
    --end
end

function UILogin:DestoryTimer()
    if self.mTimer then
        utimer.remove(self.mTimer)
        self.mTimer = nil
    end
end

function UILogin:DestoryLoginTimer()
    if self.mLoginTimer then
        utimer.remove(self.mLoginTimer)
        self.mLoginTimer = nil
    end
end

function UILogin:DestoryHttpLoginTimer()
    if self.mHttpLoginTimer then
        utimer.remove(self.mHttpLoginTimer)
        self.mHttpLoginTimer = nil
    end
end

function UILogin:BindEvent()
    self:RegisterOnClick(self.btNotice, self.OnNoticeBtnClick)
    self:RegisterOnClick(self.bt_login, self.onEnterClick)
    self:RegisterOnClick(self.Btn_SDK, self.onClick_SdkAccountCenter)
    self:RegisterOnClick(self.Btn_Repair, self.onClick_Repair)
end

function UILogin:onClick_SdkAccountCenter()
    LoginSDK.GetInstance():ShowAccountCenter()
end

function UILogin:onClick_Repair()
    logicMgr.LoginManager.showRepairGameTips();
end

function UILogin:OnSwitchAccountSuccess(jsonStr)
    local data = getJsonStr(jsonStr)
    printError("======>>>sdk 账号切换")
    dump(data)
    if data then
        self:LoginSDKSucess(data.userID, data.token ,data.channal, data.subChannel)
    end
end

function UILogin:InitSDKSuccess()
    if not isInit then
        isInit = true
        self.sdk_controller.selectedIndex = 1
        SDKManager.Login()
    end
end
    

function UILogin:LoginSDKSucess(uid, token ,channel,subChannel)
    Config.isU8sdkLoginOut = false
    self:RefreshClickState(false)
    logError("sdk 登录成功")
    Config.SDK_SubChannel = subChannel
    loginServerCount = 5;
    if AppConst.forceChannel > 0 then
        if Application.platform == RuntimePlatform.IPhonePlayer then
            channel = AppConst.forceChannel
            Config.InitFormatUrl(AppConst.forceChannel)
        elseif Application.platform == RuntimePlatform.Android then
            channel = AppConst.forceChannel
            Config.InitFormatUrl(AppConst.forceChannel)
        end
    else
        if tonumber( channel) == 39 and (tonumber(subChannel) ~= nil) and (tonumber(subChannel) == 492 or tonumber(subChannel) == 493 or (tonumber(subChannel) >= 511 and tonumber(subChannel) <= 530) or (tonumber(subChannel) >= 547 and tonumber(subChannel) <= 747) )then
            channel = tonumber(subChannel)
            Config.InitFormatUrl(channel)
            printError("渠道号39，子渠道号492,493,511--530,547--747,预留渠道==", subChannel)
        else
            Config.InitFormatUrl(channel)
        end
    end
    TAManager.UserSet("u_id", tostring(uid))
    TAManager.UserSet("channel", tostring(channel))
    TAManager.UserSet("sub_channel", tostring(subChannel))
    TAManager.UserSet("device_id", SystemInfo.deviceUniqueIdentifier)

    logicMgr.LoginManager.user_id = tostring(uid)

    local callBack = function()
        --测试数据请勿删除
        --uid = 49503
        --token = "605a5e1906109b7cec0be58f2c4c51bb"
        --[[

        TAManager.TrackByDictionary("login_http_server")

        self:RegisterOnClick(self:GetChild("Btn_SelectServer"),function()
            logicMgr.LoginManager.RefreshServerList(true)
            showUI(PanelNames.UIServer)
            CtrlManager.GetCtrl(PanelNames.UIServer):SetSelectMode()
        end)
        ]]
        TAManager.TrackByDictionary("request_server_list");
        --local filePath = Util.DataPath;
        --local locAppVersion = AppConst.appVersion;
        --local fileData = io.open(filePath .. locAppVersion .. "_files.txt", "rb");
        --if fileData ~= nil then
        --    local isDataOk = true;
        --    for line in fileData:lines() do
        --        local array = string.split(line, "|");
        --        if #array >= 3 then
        --            local fileDataPath = filePath .. array[1];
        --            local fileDataItem = io.open(fileDataPath, "rb");
        --            if fileDataItem == nil then
        --                isDataOk = false;
        --                break;
        --            else
        --                fileDataItem:close();
        --                local md5 = Util.md5file(fileDataPath);
        --                if tostring(md5) ~= tostring(array[2]) then
        --                    isDataOk = false;
        --                    break;
        --                end
        --            end
        --        end
        --    end
        --    fileData:close();
        --    if not isDataOk then
        --        Util.WriteToFile("version.txt", AppConst.originVersion, false);
        --        self:gameABError();
        --        return;
        --    end
        --end

        logicMgr.LoginManager.HttpToServerInfo(function()
            jsonStr =
            {
                userId = uid,
                token = token,
                channel = channel,
                subChannel = subChannel,
                serverId = AppConst.ServerId,
                deviceId = SystemInfo.deviceUniqueIdentifier,
                ip = Util.GetIP()
            }
            if jsonStr.ip == nil then
                jsonStr.ip = "192.0.0.1"
            end
            print("====", json.encode(jsonStr))

            self:httpVerifyLoginU8();
        end, EnumConst.LoginPlatform.U8);
    end

    logicMgr.NoticeManager.ConstraintShowNotice(callBack)
end

function UILogin:gameABError()
    logicMgr.LoginManager.showLoginTips("更新出现网络波动，请重新打开游戏", function(isOpen)
        if isOpen then
            CtrlManager.GetCtrl(PanelNames.UILoginTips).updateShowType(2, function()
                -- 强杀游戏
                logicMgr.LoginManager.QuitGame()
            end);
        else
            -- 强杀游戏
            logicMgr.LoginManager.QuitGame()
        end
    end, 2);
end

function UILogin:httpVerifyLoginU8()
    if jsonStr == nil then
        print("httpVerifyLoginU8 jsonStr == nil");
        return;
    end
    loginHandler.R_HttpVerifyLogin(EnumConst.LoginPlatform.U8, jsonStr, function(success, msgdata)
        self:RefreshClickState(false)
        if success then
            self:updateLoginData(msgdata);
        else
            TAManager.TrackByDictionary("http_server_result", { result = "fail" })
            logicMgr.LoginManager.showLoginTips("Sys_MsgServerWeakNetwork", function(isOpen)
                if isOpen then
                    CtrlManager.GetCtrl(PanelNames.UILoginTips).updateShowType(2, function()
                        self:httpVerifyLoginU8();
                    end);
                else
                    self:httpVerifyLoginU8();
                end
            end, 2);
        end
    end)
end

function UILogin:updateLoginData(msgdata)
    local v = decodeJsonStrToTabel(msgdata)
    dump(v);
    if v ~= nil and v.code == 0 then
        local defaultServerInfo = {};
        local serverId = v.recommendServerId or 0;
        defaultServerInfo.serverId = serverId;
        defaultServerInfo.name = "";
        defaultServerInfo.ip = v.serverIp or "";
        defaultServerInfo.gamePort = v.serverPort or 0;
        defaultServerInfo.loginUrl = ""
        defaultServerInfo.state = v.state;
        defaultServerInfo.version = v.version or "1.0.0";
        defaultServerInfo.time = tonumber(tostring(v.openServerTime));
        logicMgr.LoginManager.SetDefaultServerInfo(defaultServerInfo);
        logicMgr.LoginManager.SetLoginRecordServerId(serverId, v.userId or "");
        AppConst.ServerId = serverId;

        TAManager.TrackByDictionary("http_server_result", { result = "success" })
        LoginSDK.GetInstance():SubmitExtraData(1, "", "", "1", AppConst.ServerId);
        logicMgr.LoginManager.SetUserKey(v["userId"])
        G.serverData.token = v.token
        AppConst.UserToken = G.serverData.token
        AppConst.UserId = v.userId;

        logicMgr.LoginManager.ChechServerStatus(function()
            local function successCallBack()
                loginHandler.R_LoginUser();
            end
            logicMgr.LoginManager.ConnectSocket(successCallBack);
        end);
    else
        printError("v.code====", v.code)
        local json = decodeJsonStrToTabel(v.code)
        if json and type(json) == "table" then
            if json.banned then
                local timestr = os.date("%Y-%m-%d %H:%M", json.endTime)
                LoginManager.LoginShowException(json.bannedType, timestr)
            end
        else
            UISysTips.AddMsgErrorCode(v.code)
            if v.code ~= nil and 100009 == tonumber(v.code) then
                Config.isU8sdkLoginOut = true;
            end
        end
    end
end

function UILogin:httpLoginWhenFullU8()
    self:DestoryHttpLoginTimer();
    if loginServerCount < 0 then
        logicMgr.LoginManager.showLoginTips("Sys_MsgServerAllFull", function(isOpen)
            if isOpen then
                CtrlManager.GetCtrl(PanelNames.UILoginTips).updateShowType(2, function()
                    Config.isU8sdkLoginOut = true;
                end);
            else
                Config.isU8sdkLoginOut = true;
            end
        end, 2);
        return;
    end
    self.mHttpLoginTimer = utimer.timeCall(function()
        loginServerCount = loginServerCount - 1;
        loginHandler.R_HttpLoginWhenFull(function(success, msgdata)
            self:RefreshClickState(false)
            if success then
                self:updateLoginData(msgdata);
            else
                TAManager.TrackByDictionary("http_server_result", { result = "fail" })
                logicMgr.LoginManager.showLoginTips("Sys_MsgServerWeakNetwork", function(isOpen)
                    if isOpen then
                        CtrlManager.GetCtrl(PanelNames.UILoginTips).updateShowType(2, function()
                            self:httpLoginWhenFullU8();
                        end);
                    else
                        self:httpLoginWhenFullU8();
                    end
                end, 2);
                logError(msgdata);
            end
        end)
    end, 1000, 1);
end

function UILogin:updateServerId()
    if Config.lastLoginServerId > 0 then
        if (Application.platform == RuntimePlatform.Android or Application.platform == RuntimePlatform.IPhonePlayer) and Config.isOpenSDK then
            if jsonStr ~= nil then
                jsonStr.serverId = Config.lastLoginServerId;
            end
        else
            Config.ChangeServer = true;
        end
        AppConst.ServerId = Config.lastLoginServerId;
        Config.lastLoginServerId = 0;
    end
end

function UILogin:setServerState(openTime, state, updateUrl)
    serverOpenTime = openTime;
    serverState = state;
    forceUpdateUrl = updateUrl;
    self:updateOpenTipsPanelState();
end

--- 默认使用本地记录的账号/密码
function UILogin:InitAccount( )
    local acc = Util.GetUserName();
    if acc ~= nil then
        self.inputAccount.text = acc;
    end

    local pwd = Util.GetPassword();
    if pwd ~= nil then
        self.pwd_input.text = pwd;
    end
end

--- 点击登录
function UILogin:onEnterClick()
    if (Application.platform == RuntimePlatform.Android or Application.platform == RuntimePlatform.IPhonePlayer) and Config.isOpenSDK then
        if isClick then
            logError("isClick 问题")
            return;
        end
        
        if Config.isU8sdkLoginOut then
            logError("isU8sdkLoginOut == true")
            -- 调起SDK登录
            if Application.platform == RuntimePlatform.IPhonePlayer then
                if LoginSDK.GetInstance():IsU8Init() then
                    self:RefreshClickState(true)
                    SDKManager.Login()
                end
            else
                if true --[[LoginSDK.GetInstance():IsU8Init()]] then
                    self:RefreshClickState(true)
                    SDKManager.Login()
                end
            end
        else
            logError("isU8sdkLoginOut == false")
            if serverState ~= nil and serverOpenTime ~= nil then
                local nowTime = os.time()
                if serverOpenTime > nowTime or serverState == Server_ENU_State.Repair then
                    self:RefreshClickState(true)
                    if isOpenTipsPanel then
                        Http.Get(Config.ServerMaintenanceUrl, "", function(success, str)
                            if success then
                                str = decodeJsonStrToTabel(str)
                                str = str.content
                                showUI(PanelNames.UIMaintenanceMsg, str, serverOpenTime, EnumConst.MaintenanceUpdateType.maintenance, forceUpdateUrl);
                            else
                                showUI(PanelNames.UIMaintenanceMsg, "", serverOpenTime, EnumConst.MaintenanceUpdateType.maintenance, forceUpdateUrl);
                            end
                            self:RefreshClickState(false)
                        end)
                        self:updateOpenTipsPanelState();
                    else
                        serverState = nil;
                        serverOpenTime = nil;
                        isOpenTipsPanel = true;
                        self:httpVerifyLoginU8();
                    end
                else
                    serverState = nil;
                    serverOpenTime = nil;
                    isOpenTipsPanel = true;
                    self:httpVerifyLoginU8();
                end
            end
        end
        return;
    end

    Config.isU8sdkLoginOut = false
    if not Util.NetAvailable then
        UISysTips.AddMsg("请检查网络信号");
        return;
    end
    local input_account_content = self.inputAccount.text
    if #input_account_content == 0 then
        return
    end

    logicMgr.LoginManager.user_id = self.inputAccount.text
    loginServerCount = 5;
    local callback = function()
        if self.isDestroy then
            return
        end
        local localJsonStr = { username = input_account_content,
                               deviceId = SystemInfo.deviceUniqueIdentifier,
                               ip = Util.GetIP(),
                               serverId = 0}

        if Config.ChangeServer == true then
            Config.ChangeServer = false;
            localJsonStr.serverId = AppConst.ServerId;
        end

        print("====", json.encode(localJsonStr))

        loginHandler.R_HttpVerifyLogin(EnumConst.LoginPlatform.PC, localJsonStr, function (success, msgdata)
            if success then
                --记录userkey
                local _accountName = input_account_content
                logicMgr.LoginManager.SetUserKey(_accountName)

                local v = decodeJsonStrToTabel(msgdata)
                if v ~= nil and v.code == 0 then
                    logicMgr.LoginManager.SetUserKey(v["userId"])
                    Util.SetUserName(_accountName)

                    G.serverData.token = v.token
                    AppConst.UserToken = G.serverData.token
                    AppConst.UserId = v.userId

                    -- 临时测试用的
                    local defaultServerInfo = {};
                    local serverId = v.recommendServerId or 0;
                    defaultServerInfo.serverId = serverId;
                    defaultServerInfo.name = "";
                    defaultServerInfo.ip = v.serverIp or "";
                    defaultServerInfo.gamePort = v.serverPort or 0;
                    defaultServerInfo.loginUrl = ""
                    defaultServerInfo.state = v.state;
                    defaultServerInfo.version = v.version or "1.0.0";
                    defaultServerInfo.time = tonumber(tostring(v.openServerTime));
                    logicMgr.LoginManager.SetDefaultServerInfo(defaultServerInfo);
                    AppConst.ServerId = serverId;

                    logicMgr.LoginManager.DirectLoginPC(function()
                        local function successCallBack()
                            loginHandler.R_LoginUser();
                        end
                        logicMgr.LoginManager.ConnectSocket(successCallBack);
                    end);
                else
                    if v.banned then
                        local timestr = os.date("%Y-%m-%d %H:%M", v.endTime)
                        LoginManager.LoginShowException(v.bannedType, timestr)
                    else
                        UISysTips.AddMsgErrorCode(v.code)
                    end
                end
            end
        end)
    end
     
    logicMgr.NoticeManager.ConstraintShowNotice(callback)
end

function UILogin:updateOpenTipsPanelState()
    self:DestoryLoginTimer()
    self.mLoginTimer = utimer.timeCall(function()
        isOpenTipsPanel = false;
    end,60 * 1000, 1)
end

function UILogin:OnNoticeBtnClick()
    this.OnShowAnnouncement();
end

function UILogin:OnShowAnnouncement()
    loginHandler.getAnnouncement(function (msg)
        UIWaiting.HideWaiting();
        local v = decodeJsonStrToTabel(msg);
        if v ~= nil and v.code == 0 then
            showUI(PanelNames.UIAnnouncement, v);
        end
    end);
end

--- 登录成功
-- exitRole:true 有角色
function UILogin:onLoginUserSucess(exitRole)
    LoginManager.exist_role = exitRole and 0 or 1
    if exitRole then
        TAManager.TrackByDictionary("role_exist",{exist="1"})
        --TODO 这个Config.autoLogin 有用？  断线重连还没有处理
        if Config.autoLogin then
            Config.autoLogin = false;
            return;
        end
        logicMgr.LoginManager.SetLoginType(EnumConst.LoginState.Login)

        local bankName = AudioManager.GetLanguageBank()
        AudioManager.LoadBankAsync(bankName,nil)
    else
        TAManager.TrackByDictionary("role_exist",{exist="0"})
        --默认起名
        local default = HelperFunc.GetDefaultName() --logicMgr.LoginManager.GetUserKey()
        loginHandler.R_CreatePlayer(default)
        --local create = CtrlManager.GetCtrl(PanelNames.UICreateName);
        --if create ~= nil then
        --    create.Init();
        --end
        --closeUI(PanelNames.UILogin);
        logicMgr.LoginManager.SetLoginType(EnumConst.LoginState.Create)
    end

    -- TAManager.UserSet("new_player", LoginManager.exist_role)
end
return UILogin
